<template>
    <el-form ref="smsLoginForm" :model="smsFormData" status-icon :rules="smsRules" label-width="120px"
        class="demo-smsFormData">
        <el-form-item label="手机号" prop="phone" class="captcha number1">
            <el-input v-model="smsFormData.phone" class="captcha78787" maxlength="11" />
            <div class="captchaBox" @click="sendSms">{{ desc }}</div>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
            <el-input v-model="smsFormData.code" type="text" autocomplete="off" maxlength="5" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(smsLoginForm)">登录</el-button>
        </el-form-item>
    </el-form>
    <!-- <video src="../../assets/video/window.mp4" muted="muted" loop="loop" autoplay="autopl"></video> -->
</template>

<script setup>
import { reactive, ref, onUnmounted } from 'vue'
import { validatePassword, validateUsername, validateCaptcha, smsRules, useSubmitForm } from "../../composition/login/validate"

//引入发送请求的方法
import * as api from "@/api/users.js"
//引入发送请求的方法
import { loadRouteLocation, useRouter } from "vue-router"
//引入消息提示
import { ElMessage, ElLoading } from 'element-plus'
//引入store
import { useUser } from "@/store/users"
let router = useRouter()
//使用store
let userStore = useUser()
let loadingInstance = null;
let validateSuccess = async () => {
    console.log('检验成功99999');
    //发起登入请求的时候就要加载loading的加载框
    loadingInstance = ElLoading.service({
        text: "正在登陆...",
        background: 'rgba(0,0,0,.4)'
    })
    //发送短信登录请求
    try {
        let res = await api.smsApi(smsFormData.code)
        //关闭loading加载动画框
        loadingInstance.close()
        console.log(494949);
        //存储token，存到sessionStorage
        sessionStorage.setItem('my-token', res.data.token)
        //存储用户信息
        console.log(696969);
        userStore.$patch({
            userInfo: res.data.userInfo
        })
        //页面要跳转
        console.log(898989);
        router.push("/")
    } catch (e) {
        console.log(e);
        //登入检验失败，也要关闭loading动画
        loadingInstance.close()
    }
}
let validateFailed = () => {
    console.log('校验失败');

}


let submitForm = useSubmitForm(validateSuccess, validateFailed)
const smsLoginForm = ref()
//检验验证码

const smsFormData = reactive({
    phone: '',
    code: '',
})
//短信登录流程
//1.输入手机号，点击发送按钮，获取短信验证码
//短信验证码需要进行倒计时提示
//手机验证码同一个手机，一分钟只能发送一次，一天一个手机号只能发送6次


//2.输入短信验证码，进行登录请求
//声明一个响应式变量，改变按钮中间的文字
let desc = ref('点击发送验证码')
//引用定时器，便于组件卸载的时候，清除定时器
let timeDwonInterval = null;
//处理用户频繁点击的问题
//应用开关的思路
let isClick = false;//初始时用户未点击
let sendSms = async () => {
    if (!isClick) {
        console.log('触发咯');
        //获取发起短信验证码的请求
        try {
            let res = await api.getSmsCode(smsFormData.phone)
            //给消息提示
            ElMessage({
                message: '短信验证码发送成功',
                type: 'success',
            })
            // console.log(res,57577777777777777);
            //调用倒计时
            timeDwonInterval = timeDwon(5, desc, '秒后发送', desc.value, () => {
                //让点击状态isClick恢复到未点击
                isClick = false

            })

        } catch (e) {
            // console.log(e);
            //将按钮开关重置
            isClick = false;
            ElMessage({
                message: e,
                type: 'error',
            })
            return

        }
    }
    //标记isClick已经被点击了
    isClick = true;
}
//短信倒计时的方法
/**
 * @param {number} timer 倒计时的时间
 * @param {object} param    需要变更的响应式变量
 * @param {String} msg  倒计时秒数的文字
 * @param {String} enMsg    倒计时结束之后，回显的文字
 * @param {Function} cb 倒计时结束之后回调的函数
 */

//封装的思路，目的就是为了使用能够变得简单，复杂逻辑放在函数内部

//字符串.padStart('希望几位数'，'用什么字符去补')
let timeDwon = (timer = 5, param, msg, endMsg, cb) => {
    //实现思路核心就是间隔定时器
    let count = timer
    //一调用倒计时函数，就要显示倒计时的秒数
    param.value = (count + "").padStart(2, 0) + msg
    let interval = setInterval(() => {
        count--
        if (count < 0) {
            //清除定时器
            clearInterval(interval)
            //倒计时结束
            param.value = endMsg
            //回调传入的函数
            //为undefined执行后面的语句 
            // cb??cb()
            cb && cb()
            return
        }
        param.value = (count + "").padStart(2, 0) + msg
    }, 1000)
    //返回定时器的引用
    return interval
}
//组件卸载的钩子
onUnmounted(() => {
    //卸载定时器
    console.log('组件被卸载了');
    //如果定时器存在，组件卸载的时候也需要清除定时器
    if (timeDwonInterval) {
        clearInterval(timeDwonInterval)
    }
})
</script>

<style lang="scss" scoped>
//最外层的box
.el-form {
    :deep(.el-form-item__label) {
        color: white
    }

    //内层输入框
    .el-input {
        width: 260px;
    }

    //内层第一个
    .number1 {
        margin-top: 50px;
    }
}

//短信登录按钮的样式



.captcha {
    .el-input {
        width: 150px;

    }

    :deep(.el-input__wrapper) {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
        border-right: 0;
        box-shadow: none;
    }
}

.captchaBox {
    box-shadow: none;
    height: 32px;
    width: 100px;
    font-size: 14px;
    // box-shadow: 0 0 0 1px #dcdfe6;
    transition: var(--el-transition-box-shadow);
    background-color: white;
    border-left: 0;
    border-radius: 0 4px 4px 0;
    cursor: pointer;
    text-decoration: underline;
    color: rgb(136, 136, 136);
    padding: 0 10px 0 0;
    user-select: none;

}

// :deep(.el-form-item__label){
//         color:white
//     }
</style>
